using MediatR;
using WorkOrder.Domain;
using B.S.BaseData.Api.Write.Applicantion.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 处理退款申请处理器
    /// </summary>
    public class ProcessRefundApplicationHandler : IRequestHandler<ProcessRefundApplicationCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<RefundApplication> _refundRepository;

        public ProcessRefundApplicationHandler(IBaseRepository<RefundApplication> refundRepository)
        {
            _refundRepository = refundRepository;
        }

        public async Task<APIResult<bool>> Handle(ProcessRefundApplicationCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> result = new APIResult<bool>();
            result.Code = ApiEnum.Success;
            result.Msg = "处理成功";

            try
            {
                // 从数据库获取退款申请
                var refundApplication = _refundRepository.GetAll().FirstOrDefault(r => r.RefundId == request.RefundId);

                if (refundApplication == null)
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "退款申请不存在";
                    return result;
                }

                // 检查申请状态
                if (refundApplication.ApplicationStatus != "待处理")
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "该退款申请已被处理，无法重复处理";
                    return result;
                }

                // 更新退款申请状态
                refundApplication.ApplicationStatus = request.ProcessResult;
                refundApplication.ProcessorName = request.ProcessorName;
                refundApplication.ProcessTime = DateTime.Now;
                refundApplication.ProcessRemarks = request.ProcessRemarks;
                refundApplication.UpdateTime = DateTime.Now;

                // 保存到数据库
                await _refundRepository.UpdateAsync(refundApplication);

                result.Data = true;
                result.Msg = request.ProcessResult == "已处理" ? "退款申请已确认" : "退款申请已拒绝";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = $"处理失败: {ex.Message}";
                Console.WriteLine($"处理退款申请失败: {ex}");
            }

            return result;
        }
    }
} 